import Taro from "@tarojs/taro";
import {createProject, getRecomProjects, getProject, searchProjects, getProjectsByIds} from '../services/api';

export default {
  namespace: 'project',

  state: {
    list: [],
    item: {},
  },

  effects: {
    * create({payload}, {call, put}) {
      const result = yield call(createProject, payload);
      if (result && result.code === 0) {
        Taro.showToast({
          title: result.message,
          icon: 'none',
          duration: 1000,
        });

        setTimeout(() => {
          Taro.navigateBack();
        }, 1000);
      }
    },

    * getRecom({payload}, {call, put}) {
      const result = yield call(getRecomProjects, payload);
      if (result && result.code === 0) {
        yield put({
          type: 'save',
          payload: {
            list: result.data,
          },
        });
      }
    },

    * getByIds({payload}, {call, put}) {
      const result = yield call(getProjectsByIds, payload);
      if (result && result.code === 0) {
        yield put({
          type: 'save',
          payload: {
            list: result.data,
          },
        });
      }
    },

    * search({payload}, {call, put}) {
      const result = yield call(searchProjects, payload);
      if (result && result.code === 0) {
        yield put({
          type: 'save',
          payload: {
            list: result.data,
          },
        });
      }
    },

    * get({payload}, {call, put}) {
      const result = yield call(getProject, payload);
      if (result && result.code === 0) {
        yield put({
          type: 'save',
          payload: {
            item: result.data,
          },
        });
      }
    },
  },

  reducers: {
    save(state, {payload}) {
      return {
        ...state,
        ...payload,
      };
    },
  },
};
